package repository

import (
	"gitee.com/ling1314/origin-utility/db"
	"gitee.com/ling1314/origin-utility/model"
)

type vaHostSessionRepository struct{}

func (r vaHostSessionRepository) FindPage(input model.AdminSearchHostSession) (li []model.HostSession, total int64, err error) {
	d := db.GetDB().Model(&model.HostSession{})
	d.Where(" host_ip like '%" + input.HostIp + "%'")
	if input.Status != "" {
		d.Where(" status = ? ", input.Status)
	}
	if input.EndTime != 0 && input.StartTime != 0 {
		d.Where(" created_time > ? and created_time < ? ", input.StartTime, input.EndTime)
	}
	err = d.Count(&total).Limit(input.PageSize).Offset((input.Page - 1) * input.PageSize).Find(&li).Error
	return
}

func (r vaHostSessionRepository) Create(o *model.HostSession) (err error) {
	err = db.GetDB().Create(o).Error
	return
}

func (r vaHostSessionRepository) FindById(sessionId int64) (o model.HostSession, err error) {
	err = db.GetDB().Where("host_session_id = ?", sessionId).First(&o).Error
	return
}

func (r vaHostSessionRepository) DeleteById(sessionId int64) error {
	return db.GetDB().Where("host_session_id = ?", sessionId).Delete(&model.HostSession{}).Error
}

func (r vaHostSessionRepository) UpdateById(o *model.HostSession) error {
	return db.GetDB().Save(o).Error
}

func (r vaHostSessionRepository) UpdateWindowSizeById(width, height string, id int64) error {
	session := model.HostSession{}
	session.Width = width
	session.Height = height
	return r.UpdateById(&session)
}

func (r vaHostSessionRepository) FindUserActionSession(userId, clusterId int64) (li []model.HostSession, err error) {
	err = db.GetDB().Where("user_id = ? and cluster_id = ? and hold_status = ?", userId, clusterId, model.VaSessionHoldForHolding).Find(&li).Error
	return
}

// FindActionSessionByAppId 根据应用ID查询活跃会话
func (r vaHostSessionRepository) FindActionSessionByAppId(appId int64) (li []model.HostSession, err error) {
	err = db.GetDB().Raw("SELECT * FROM va_host_session WHERE host_session_id IN ( "+
		" SELECT host_session_id FROM va_map_host_session_app WHERE host_session_id IN ( "+
		" SELECT host_session_id FROM va_host_session WHERE hold_status = ? "+
		" ) AND app_id = ? )", model.VaSessionHoldForHolding, appId).Scan(&li).Error
	return
}
